package ru.hh.school.commands;

import ru.hh.school.Room;
import ru.hh.school.RoomManager;
import ru.hh.school.User;
import ru.hh.school.logging.Logger;

import static ru.hh.school.util.ResourceManager.message;

public class JoinRoomCommand extends Command {
    private final RoomManager manager;

    public JoinRoomCommand(Logger logger, RoomManager roomManager) {
        super(logger);
        this.manager = roomManager;
    }

    public String getCommand() {
        return "/join";
    }

    public String getDescription() {
        return message("command.join.description");
    }

    public void process(User user, String roomName) throws InterruptedException {
        Room newRoom = manager.getRoom(roomName);
        Room oldRoom = user.getRoom();
        if (newRoom == null) {
            user.sendMessage(message("command.join.notify.user.error.room.does.not.exist", roomName));
            return;
        }
        if (newRoom.equals(oldRoom)) {
            user.sendMessage(message("command.join.notify.user.error.same.room", oldRoom.getName()));
            return;
        }
        oldRoom.delUser(user);
        newRoom.addUser(user);
        user.setRoom(newRoom);
        user.sendMessage(message("command.join.notify.user.user.join.room", roomName));
        newRoom.send(message("command.send.notify.room.user.joins.room", user.getLogin()), user);
        oldRoom.send(message("command.send.notify.room.user.leaves.room", user.getLogin()));
    }
}
